package com.fang.distributed_locks.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands.SetOption;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Service;

/**
 * @Description 分布式锁工具
 * @Author Bernie_fang
 * @Date 2024/2/19 22:11
 **/
@Service
public class LockUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @param lockKey     上锁的key
     * @param value       上锁的value,用于校验删除锁
     * @param lockSeconds 上锁的秒数
     * @return
     */
    public boolean lock(String lockKey, String value, int lockSeconds) {
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            byte[] key = lockKey.getBytes();
            Boolean set = connection.set(key, value.getBytes(), Expiration.seconds(lockSeconds), SetOption.SET_IF_ABSENT);
            if (set == null) {
                return false;
            }
            return set;
        });
    }

    public boolean isLock(String lockKey) {
        return stringRedisTemplate.opsForValue().get(lockKey) != null;
    }

    public boolean clearLock(String lockKey, String value) {
        if(stringRedisTemplate.opsForValue().get(lockKey).equals(value)){
            return stringRedisTemplate.delete(lockKey);
        }
        return false;
    }

}
